package com.open.capacity.form.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.form.dao.FormRelationDao;
import com.open.capacity.form.dao.FormSchemeinfoDao;
import com.open.capacity.form.model.FormRelation;
import com.open.capacity.form.model.FormSchemeinfo;
import com.open.capacity.form.service.FormRelationService;
import com.open.capacity.form.vo.FormRelationVo;
import com.open.capacity.model.system.SysMenu;
import com.open.capacity.model.system.SysMenuButton;
import com.open.capacity.model.system.SysMenuColumn;
import com.open.capacity.model.system.SysMenuForm;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.service.SysMenuService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.utils.PageUtil;
import com.open.capacity.vo.SysMenuVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Slf4j
@Service
public class FormRelationServiceImpl implements FormRelationService {

    @Autowired
    private FormRelationDao relationDao;

    @Autowired
    private FormSchemeinfoDao schemeinfoDao;

    @Autowired
    private SysMenuService menuService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(FormRelation relation) {
        relation.setCreateTime(new Date());

        relationDao.save(relation);
        log.info("保存表单关联：{}", relation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(FormRelation relation) {

        relationDao.updateByOps(relation);
        log.info("修改表单关联：{}", relation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(String id) {
        FormRelation relation = relationDao.findById(id);

        menuService.delete(relation.getMenuId());

        relationDao.delete(id);

        log.info("删除表单关联：{}", relation);
    }


    @Override
    public FormRelationVo findById(String id) {
        FormRelationVo result = new FormRelationVo();
        FormRelation relation = relationDao.findById(id);
        SysMenuVo menuRes = menuService.findById(relation.getMenuId());
        SysMenuVo menuVo = menuRes;
        result.setRelation(relation);
        result.setMenu(menuVo.getMenu());
        return result;
    }

    @Override
    public FormRelation findByFormId(String formId) {
        return relationDao.findByFormId(formId);
    }


    @Override
    public PageResult<FormRelation> findRelations(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<FormRelation>  list = relationDao.findList(params);
        PageInfo<FormRelation> pageInfo = new PageInfo(list);

        return PageResult.<FormRelation>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result saveOrUpdate(FormRelationVo relationVo, String keyValue) {
        int i = 0;
        FormRelation relation = relationVo.getRelation();
        FormSchemeinfo schemeinfo = schemeinfoDao.findById(relation.getFormId());
        relation.setMenuName(relationVo.getMenu().getName());
        relation.setFormName(schemeinfo.getName());

        SysMenuVo menuVo = new SysMenuVo();
        BeanUtils.copyProperties(relationVo, menuVo);
        menuVo.getMenu().setTarget("iframe");
        menuVo.getMenu().setPath("/pages/form/formRelation/previewIndex.html?id=" + relation.getFormId());
        menuVo.getMenu().setIsMenu(1);
        menuVo.getMenu().setStatus(1);
        Set<SysMenuButton> menuButtons = new HashSet<>();
        SysMenuButton btn = new SysMenuButton();
        btn.setMenuId(menuVo.getMenu().getId());
        btn.setCode("lr_add");
        btn.setName("新增");
        menuButtons.add(btn);

        btn = new SysMenuButton();
        btn.setMenuId(menuVo.getMenu().getId());
        btn.setCode("lr_edit");
        btn.setName("编辑");
        menuButtons.add(btn);

        btn = new SysMenuButton();
        btn.setMenuId(menuVo.getMenu().getId());
        btn.setCode("lr_delete");
        btn.setName("删除");
        menuButtons.add(btn);

        btn = new SysMenuButton();
        btn.setMenuId(menuVo.getMenu().getId());
        btn.setCode("lr_print");
        btn.setName("打印");
        menuButtons.add(btn);

        menuVo.setMenuBtns(menuButtons);

        SysMenu menu = new SysMenu();
        BeanUtils.copyProperties(menuVo.getMenu(), menu);
        Set<SysMenuButton> btns = menuVo.getMenuBtns();
        Set<SysMenuColumn> cols = menuVo.getMenuColumns();
        Set<SysMenuForm> forms = menuVo.getMenuForms();

        Result result =  menuService.saveOrUpdate(menu, btns, cols);

        if (result.getResp_code().equals(CodeEnum.SUCCESS.getCode())) {
            if (StringUtils.isNotEmpty(keyValue)) {
                FormRelation model = relationDao.findById(keyValue);
                if (model != null) {
                    i = relationDao.updateByOps(relation);
                }
            } else {
                relation.setId(UUIDUtils.getOriginalUUIDWithoutBar());
                relation.setCreateTime(new Date());
                relation.setMenuId(result.getData().toString());
                i = relationDao.save(relation);
            }
        }


        return Result.succeed("操作成功");
    }


}
